package com.hb.core.base;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.collections.CollectionUtils;

import java.util.List;
import java.util.Objects;

/**
 * @description: 分页查询
 * @projectName: zhb-frame-build
 * @author: zhouhaizhi
 * @createTime: 2021/8/16 14:47
 * @version:1.0
 */
public class PageFactory {

    private static final String ASC = "asc";

    private static final int PAGE_SIZE = 20;

    private static final int PAGE_NO = 1;

    private static <T> Page<T> defaultPage() {
        return new Page<>(PAGE_NO, PAGE_SIZE);
    }

    public static <T> Page<T> createPage(PageCondition pageCondition) {
        if (Objects.isNull(pageCondition)) {
            return defaultPage();
        }

        int pageSize = 20;
        int pageNo = 1;

        if (!Objects.isNull(pageCondition.getPageSize())) {
            pageSize = pageCondition.getPageSize();
        }
        if (!Objects.isNull(pageCondition.getPageNum())) {
            pageNo = pageCondition.getPageNum();
        }
        Page<T> page = new Page<>(pageNo, pageSize);
        List<OrderField> orderFields = pageCondition.getOrderByFieldList();
        if (CollectionUtils.isEmpty(orderFields)) {
            return page;
        }
        for (OrderField orderField : orderFields) {
            if (ASC.equalsIgnoreCase(orderField.getSort())) {
                page.addOrder(OrderItem.asc(orderField.getFieldName()));
            } else {
                page.addOrder(OrderItem.desc(orderField.getFieldName()));
            }
        }
        return page;
    }
}
